
import { animate, style, transition, trigger } from '@angular/animations';
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  OnInit,
} from '@angular/core';
import { Router } from '@angular/router';
import { combineLatest, empty, merge, of, Subscription } from 'rxjs';
import { pluck, switchMap } from 'rxjs/operators';
import { AlbumService } from './services/apis/album.service';
import { AlbumInfo, Category, Track } from './services/apis/types';
import { CategoryService } from './services/business/category.service';
import { PlayerService } from './services/business/player.service';
import { OverlayRef, OverlayService } from './services/tools/overlay.service';
import { MessageService } from './share/components/message/message.service';
interface InPlayerInfo {
    trackList: Track[];
    currentIndex: number;
    currentTrack: Track;
    album: AlbumInfo;
    playing: boolean;
  };
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [
    trigger('fadePlayer', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('.2s', style({ opacity: 1 })),
      ]),
      transition(':enter', [
        style({ opacity: 0 }),
        animate('.2s', style({ opacity: 0 })),
      ]),
    ]),
  ],
})
export class AppComponent implements OnInit {
  currentCategory: Category;
  categories: Category[] = [];
  categoryPinyin = '';
  subcategory: string[] = [];
  overlayRef: OverlayRef;
  overlaySub: Subscription;
  showLogin = false;
  showPlayer = false;
  playerInfo: InPlayerInfo;
  constructor(
    private albumServe: AlbumService,
    private cdr: ChangeDetectorRef,
    private categoryServe: CategoryService,
    private router: Router,
    private overlayService: OverlayService,
    private playerService: PlayerService
  ) {}
  ngOnInit(): void {
    this.init();
    this.watchPlayer();
  }
  private watchPlayer(): void {
    combineLatest(
      this.playerService.getTracks(),
      this.playerService.getAlbum(),
      this.playerService.getCurrentIndex(),
      this.playerService.getCurrentTrack(),
      this.playerService.getPlaying()
    ).subscribe(([trackList, album, currentIndex, currentTrack, playing]) => {
      this.playerInfo = {
        trackList,
        album,
        currentIndex,
        currentTrack,
        playing,
      };
      if (trackList.length) {
        this.showPlayer = true;
        this.cdr.markForCheck();
      }
    });
  }
  showOverlay(): void {
    this.overlayRef = this.overlayService.create({
      fade: true,
      backgroundColor: 'rgba(0,0,255, .32)',
    });
    console.log(this.overlayRef);
    this.overlaySub = merge(
      this.overlayRef.backdropClick(),
      this.overlayRef.backdropKeyup().pipe(
        pluck('key'),
        switchMap((key) => {
          return key.toUpperCase() == 'ESCAPE' ? of(key) : empty();
        })
      )
    ).subscribe(() => {
      this.hideOverlay();
    });
  }
  hideOverlay(): void {
    if (this.overlaySub) {
      this.overlaySub.unsubscribe();
      this.overlaySub = null;
    }
    this.overlayRef.dispose();
    this.overlayRef = null;
  }
  private init(): void {
    combineLatest(
      this.categoryServe.getCategory(),
      this.categoryServe.getSubCategory()
    ).subscribe(([category, subcategory]) => {
      if (category !== this.categoryPinyin) {
        this.categoryPinyin = category;
        if (this.categories.length) {
          this.setCurrentCategory();
        }
      }
      this.subcategory = subcategory;
    });
    this.getCategories();
  }
  private getCategories(): void {
    this.albumServe.categories().subscribe((categories) => {
      this.categories = categories;
      this.setCurrentCategory();
      this.cdr.markForCheck();
    });
  }
  changeCategory(category: Category): void {
    // if (this.currentCategory.id !== category.id) {
    // this.currentCategory = category;
    this.categoryServe.setCategory(category.pinyin);
    this.router.navigateByUrl('/albums/' + category.pinyin);
    //   console.log('--------------');
    // }
  }
  private setCurrentCategory(): void {
    this.currentCategory = this.categories.find(
      (item) => item.pinyin === this.categoryPinyin
    );
  }
  closedPlayer(): void {
    this.playerService.clear();
    this.showPlayer = false;
  }
}



